/*
 * $AIST_Release: 0.9.0 $
 * Copyright 2011 Information Technology Research Institute, National
 * Institute of Advanced Industrial Science and Technology
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package util

import scala.util.Random

import java.lang.Iterable
import java.io.File
import java.io.FileOutputStream

import org.apache.hadoop.fs._
import org.apache.hadoop.conf.Configuration

import com.google.protobuf.ByteString
import com.google.protobuf.CodedOutputStream

import pbdata.Tables._

object RandomPBTableMaker {

  val LETTERS = (('a' to 'z') ++ ('A' to 'Z')).toList
  val WORD_LENGTH = (3 to 12).toList // 長さが適当かどうかは不明
  val encoding = "UTF-8"
  lazy val localFS = FileSystem.getLocal(new Configuration)

  def mkFile(randGen: Random, nrec: Int, path: Path): List[(Array[Byte], Array[Byte])] = {
    def nextBytes() = {
      val len = WORD_LENGTH(randGen.nextInt(WORD_LENGTH.size))
      val chars = for (_ <- 0 until len) yield LETTERS(randGen.nextInt(LETTERS.size))

      new String(chars.toArray).getBytes(encoding)
    }

    val builder = Table.newBuilder()

    val values = for (_ <- (1 to nrec)) yield {
      val key   = nextBytes()
      val value = nextBytes()

      builder.addData(KeyValue.newBuilder()
          .setKey(ByteString.copyFrom(key))
          .setValue(ByteString.copyFrom(value))
      )

      (key, value)
    }

    val os = localFS.create(path)
    val cos = CodedOutputStream.newInstance(os);
    try {
      builder.build().writeTo(os)
    } finally {
      cos.flush()
      os.close()
    }

    return values.toList;
  }
}
